# -*- coding:utf-8 -*-
# @Time: 2020/9/7 14:18
# @Author: gupeng
# @File: lock.py
# @Desc: 锁--nx测试,nx:值不存在时设置，xx:值存在时设置
VALUE_OF_LOCK = 'locking'


class Lock:
    def __init__(self, client, key):
        self.client = client
        self.key = key

    def acquire(self):
        """
        尝试获取锁
        :return: 成功返回true，否则返回false
        """
        result = self.client.set(self.key, VALUE_OF_LOCK, nx=True)
        return result is not None

    def release(self):
        """
        尝试释放锁
        :return: 成功返回true，否则返回false
        """
        return self.client.delete(self.key) == 1
